<template>
  <div>
    <nav-bar title="首页常用功能">
      <template v-slot:right>
        <span class="fontSize16" @click="saveModel">保存</span>
      </template>
    </nav-bar>
    <div class="personal maxinBox">
      <div class="backgroundfff" style="padding: 0.9375rem;">
        <div class="titleModel">正在使用的功能模块</div>
        <van-row>
          <work-piece action="del" :data="item" v-for="(item, index) in modelList.useList" :key="index" @click.native="delUse(item)"></work-piece>
        </van-row>
      </div>
      <div class="marginTop5 backgroundfff" style="padding: 0.9375rem;">
        <div class="titleModel">未使用的功能模块</div>
        <van-row>
          <work-piece action="add" :data="item" v-for="(item, index) in modelList.unUseList" :key="index" @click.native="addUse(item)"></work-piece>
        </van-row>
      </div>
      <div class="center" v-if="$route.params.save === true">
        <van-button size="small" type="info" @click="$router.push({name: 'Dashbord'})">保存</van-button>
      </div>
    </div>
  </div>
</template>

<script>

  import myAPI from '../../../../api/myAPI.js'
  import WorkPiece from '../components/WorkPiece.vue'
  export default {
    components: {
      WorkPiece
    },
    data() {
      return {
        modelList: {
          useList: [],
          unUseList: [],
        }
      }
    },
    methods: {
      getUerModel() {
        myAPI.getFunction().then(res => {
          this.modelList.useList = res.result.map(item => {
            if (item.openStatus === 1) {
              return item
            }
          }).filter(Boolean)
          this.modelList.unUseList = res.result.map(item => {
            if (item.openStatus === 0) {
              return item
            }
          }).filter(Boolean)
        })
      },
      // 从常用模块删除
      delUse (data) {
        this.modelList.useList.splice(this.modelList.useList.indexOf(data), 1)
        this.modelList.unUseList.push(data)
      },
      // 从不常用模块添加
      addUse (data) {
        if (this.modelList.useList.length >= 7) {
          this.$toast('首页功能最多可设置7个,请先删除')
        } else {
          this.modelList.unUseList.splice(this.modelList.unUseList.indexOf(data), 1)
          this.modelList.useList.push(data)
        }

      },
      // 保存数据
      saveModel() {
        let arrUnUse = this.modelList.unUseList.filter(Boolean)
        let arrUse = this.modelList.useList.filter(Boolean)
        arrUnUse.map(item => {
          this.$set(item, 'openStatus', 0)
        })
        arrUse.map(item => {
          this.$set(item, 'openStatus', 1)
        })
        let arrList = arrUnUse.concat(arrUse)
        myAPI.saveFunction(arrList).then(res => {
          this.$toast.success('更新成功')
          this.modelList.useList = []
          this.modelList.unUseList = []
          this.getUerModel()
        })
      }
    },
    mounted() {
      this.getUerModel()
    }
  }
</script>
